package com.example.ioc.aspect;

import com.example.ioc.annotation.Transaction;
import com.example.ioc.util.SqlSession;
import com.example.spring.framework.aop.aspect.JoinPoint;

import java.sql.SQLException;

/**
 * @author ：wuhong-016
 * @version v1.0.0
 * @Create : 2021/1/21 14:20
 * @Description : TODO
 **/
public class TransactionAspect {

    /**
     * 开启事务
     *
     * @param joinPoint
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public void before(JoinPoint joinPoint) throws SQLException, ClassNotFoundException {
        SqlSession.openSession();
        if (joinPoint.getMethod().isAnnotationPresent(Transaction.class)) {
            SqlSession.openTransaction();
        }
    }

    /**
     * 提交事务
     *
     * @param joinPoint
     * @throws SQLException
     */
    public void after(JoinPoint joinPoint) throws SQLException {
        SqlSession.commit();
        SqlSession.closeSession();
    }

    /**
     * 回滚事务
     *
     * @param joinPoint
     * @param ex
     * @throws SQLException
     */
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) throws SQLException {
//        if (joinPoint.getMethod().isAnnotationPresent(Transaction.class)) {
        SqlSession.rollback();
//        } else {
//            SqlSession.commit();
//        }
        SqlSession.closeSession();
    }

}
